<template>
    <div id="leftdown" style="width: 600px; height: 400px;"></div>
</template>
<script setup>
  import { onMounted, defineProps, watch, nextTick } from 'vue';
  import * as echarts from 'echarts';
  
  // 定义 props，接收父组件传递的数据
  const props = defineProps({
    childData3: Array
  });
  
  let myChart = null; // 存储 ECharts 实例
  
  const initECharts = () => {
    const echartsContainer = document.getElementById("leftdown");
    if (myChart) {
      // 如果已经存在 ECharts 实例，则先销毁它
      myChart.dispose();
    }
    // 初始化 ECharts 实例
    myChart = echarts.init(echartsContainer);
    // 检查childData1是否已定义
    if (!props.childData3 || props.childData3.length === 0) {
      console.warn('childData1 is not ready yet.');
      return; // 如果数据未准备好，直接返回不执行后续逻辑
    }

    const datas = [];
    props.childData3.forEach(item => {
      datas.push(
        { value: item.self_saless, carname: item.carname },
      { value: item.all_carsalse , carname: '其他' }
      );
     
    });
    const option = {
    tooltip : {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
    },
    legend: {
        orient: 'vertical',
        left: 'left',
        data: ['本身','所有']
    },
    series : [
        {
            name: '销售量占比',
            type: 'pie',
            radius : '55%',
            center: ['50%', '60%'],
            data:datas,
            itemStyle: {
                emphasis: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(49, 112, 167, 0.5)'
                }
            }
        }
    ]
};
    myChart.setOption(option);
  };
  
  // 修改onMounted钩子
  onMounted(async () => {
    await nextTick(); // 等待DOM更新
    initECharts();
  });
  
  // 修改watcher回调，添加async并使用nextTick
  watch(() => props.childData3, async () => {
    await nextTick(); // 等待DOM更新
    initECharts();
  }, { immediate: true });
  
</script>